package com.study.guide.codec.Marshalling;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeClientHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		//由于对象解码器已经对订购请求应答消息进行了自动解码，
        //因此，ClientHandler接收到的消息已经是解码成功后的订购应答消息。
        System.out.println("--- Receive server response : [" + msg + "]");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//在链路激活的时候循环构造10条订购请求消息，最后一次性地发送给服务端。
        for (int i = 0; i < 10; i++) {
            ctx.write(subReq(i));
        }
        ctx.flush();
	}

	private Request subReq(int i) {
        Request req = new Request();
        req.setAddress("北京市朝阳区望京SOHO 第"+(i+1)+"区 。");
        req.setPhoneNumber("188xxxxxxxxx---000"+(i+1));
        req.setProductName("Netty For Marshalling---"+(i+1));
        req.setSubReqID(i);
        req.setUserName("zhangsan---"+(i+1));
        return req;
    }

	@Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
